package com.wzh.oj.config;

import com.wzh.oj.factory.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author wzh
 */
@Configuration
public class ThreadPoolConfig {


    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        int i = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor();
//        核心线程数
         threadPoolTaskExecutor.setCorePoolSize(i*2);
//        最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(i*2);
//        阻塞队列中的最大数量
        threadPoolTaskExecutor.setQueueCapacity(i*2*10);
//        线程名称的前缀
        threadPoolTaskExecutor.setThreadNamePrefix("ThreadPoolTaskExecutor-");
//        设置线程池的拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        当调度器shutdown被调用时等待当前被调用的任务完成
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
//        线程空闲后的最大存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
//        设置自定义线程工厂
        threadPoolTaskExecutor.setThreadFactory(new MyThreadFactory(threadPoolTaskExecutor));

        threadPoolTaskExecutor.initialize();

        return  threadPoolTaskExecutor;
    }
}
